import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RenameAndMoveFiles {

    public static void main(String[] args) {
        String rootDirectory = "../root"; // 你的根文件夹路径
        File root = new File(rootDirectory);

        if (!root.exists() || !root.isDirectory()) {
            System.err.println("根目录不存在或不是一个目录。");
            return;
        }

        File[] subDirectories = root.listFiles(File::isDirectory);

        if (subDirectories != null) {
            for (File subDirectory : subDirectories) {
                processSubDirectory(subDirectory, rootDirectory);
            }
        }
    }

    private static void processSubDirectory(File subDirectory, String rootDirectory) {
        File[] files = subDirectory.listFiles();
        if (files != null) {
            Map<String, Integer> fileNameCounts = new HashMap<>(); // 用于跟踪重名文件数量

            for (File file : files) {
                if (file.isFile()) {
                    String newFileName = subDirectory.getName();
                    // 移除 "字母开口再加." 前缀
                    newFileName = removePrefix(newFileName);

                    int count = fileNameCounts.getOrDefault(newFileName, 0);
                    if (count > 0) {
                        newFileName += "_" + count; // 添加数字后缀
                    }
                    fileNameCounts.put(subDirectory.getName(), count + 1); // 更新计数

                    Path sourcePath = file.toPath();
                    Path targetPath = Paths.get(rootDirectory, newFileName + getFileExtension(file.getName()));

                    try {
                        Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                        System.out.println("文件 " + file.getName() + " 已重命名并移动到 " + targetPath);
                    } catch (IOException e) {
                        System.err.println("移动文件 " + file.getName() + " 时出错：" + e.getMessage());
                    }
                }
            }
        }
    }

    // 移除 "字母开口再加." 前缀
    private static String removePrefix(String fileName) {
        Pattern pattern = Pattern.compile("^[a-zA-Z]+\\.");
        Matcher matcher = pattern.matcher(fileName);
        if (matcher.find()) {
            return matcher.replaceFirst(""); // 移除匹配到的前缀
        }
        return fileName;
    }

    // 获取文件扩展名
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex > 0) {
            return fileName.substring(dotIndex);
        }
        return "";
    }
}
